﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Diagnostics;
using System.Text;

namespace AugmentingGeneratorMethod
{
    [Generator]
    public class AugmentingGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context)
        {
            // 自定义一个语法接收器的工厂，然后通过该工厂向已有的class类中添加新方法
            context.RegisterForSyntaxNotifications(() => new AugmentSyntaxReceiver());
        }

        public void Execute(GeneratorExecutionContext context)
        { 
            //Debugger.Launch();
            // 获得创建的语法接收器，然后通过context进行操作
            AugmentSyntaxReceiver syntaxReceiver = (AugmentSyntaxReceiver)context.SyntaxReceiver;

            // 通过语法接收器获得class类
            ClassDeclarationSyntax augmentClass = syntaxReceiver.ClassToAugment;
            //判断是否有这个类
            if (augmentClass is null)
            {
                //没有找到就不做任何事情
                return;
            }
            SourceText sourceText = SourceText.From($@"
                namespace {syntaxReceiver.SpaceToAugment.Name.GetText()}
                {{
                    public  class {augmentClass.Identifier}Data
                    {{
                        public static void GeneratedMethod()
                        {{
                            Console.WriteLine(@""{syntaxReceiver.strBuilder.ToString()}"");
                        }}
                    }}
                }}", Encoding.UTF8);

            context.AddSource("augmentClass.Generated.cs", sourceText);
        }
    }
}
